<?php
/**
 * 任务计划类的方法
 */

namespace App\Http\Controllers\Common;

use App\Enums\MallEnum;
use App\Enums\RedisKeyEnum;
use App\Enums\ActionEnum;
use App\Enums\TaskEnum;
use Carbon\Carbon;
use App\Exceptions\BasicException;
use App\Services\Tools\AliyunService;
use App\Http\Controllers\BaseController;
use App\Services\Tools\CurlService;
use Illuminate\Support\Facades\DB;      //引用DB
use Illuminate\Support\Facades\Config;  //引入配置类
use App\Services\Cache\UserCacheService;//引入用户缓存类
use Illuminate\Support\Facades\Redis;
use App\Services\Tools\{MapService, PushService, RedisService, SmsService};

class TaskController extends BaseController
{
    /**
     * 人脉语聊增加亲密度 1次/min
     */
    public function intimacyAddByChat()
    {
        $list = app('model_connection_relation')
            ->where('room_id', '>', 0)
            ->select('id','user_id','relation_user_id','today_intimacy','today_intimacy_free','intimacy_last_update_time','intimacy','type','married','class_number','grade_number')
            ->get()->toArray();
        if (empty($list)) return ;
        $classMap = MapService::connectionClassMap();
        $gradeList = app('repo_connection')->gradeList();
        $gradeMap = array_column($gradeList,null,'number');
        $date = date('Ymd');
        foreach ($list as $value) {
            if ($value['grade_number'] >= 50) continue;
            $classDetail = $classMap[$value['type']][$value['class_number']] ?? [];
            $todayIntimacyFreeMax = $classDetail['day_intimacy_free_max'] ?? 500;
            $todayIntimacyMax = $classDetail['day_intimacy_max'] ?? 1000;
            //$intimacyAddition = $classDetail['intimacy_addition'] ?? 1.0;
            $intimacyAddition = 1;
            $intimacyIncreaseRate = $classDetail['intimacy_increase_rate'] ?? 1.0;
            $intimacy = round($intimacyAddition * $intimacyIncreaseRate, 2);
            if ($value['intimacy_last_update_time'] != $date) {
                $intimacy = $intimacy <= $todayIntimacyFreeMax ? $intimacy : $todayIntimacyFreeMax;
                $intimacy = $intimacy <= $todayIntimacyMax ? $intimacy : $todayIntimacyMax;
            } else {
                $intimacy = $intimacy <= ($todayIntimacyFreeMax - $value['today_intimacy_free']) ? $intimacy : ($todayIntimacyFreeMax - $value['today_intimacy_free']);
                $intimacy = $intimacy <= ($todayIntimacyMax - $value['today_intimacy']) ? $intimacy : ($todayIntimacyMax - $value['today_intimacy']);
            }
            if ($intimacy <= 0) continue;

            $allIntimacy = $value['intimacy'] + $intimacy;
            $gradeNumber = $classNumber = 0;
            foreach ($gradeList as $v) {
                if ($allIntimacy > $v['exp']) {
                    $gradeNumber = $v['number'];
                    break;
                }
            }
            if ($value['type'] == 1) {
                foreach ($classMap[1] as $v) {
                    if ($gradeNumber >= $v['max_grade_number']) {
                        $classNumber = $v['class_number'];
                        if ($value['class_number'] <= 3 && $classNumber >= 4) {
                            $classNumber = 3;
                            $gradeNumber = 30;
                            $intimacy = isset($gradeMap[$gradeNumber+1]['exp']) ? abs($gradeMap[$gradeNumber+1]['exp'] - $value['intimacy']) : 0;
                        }
                        break;
                    }
                }
            } else {
                foreach ($classMap[2] as $v) {
                    if ($gradeNumber >= $v['max_grade_number']) {
                        $classNumber = $v['class_number'];
                        if ($value['class_number'] <= 3 && $classNumber >= 4) { //3级亲密度升4级设计问题，这里直接赠送不能直接升级，因为当前是3级，需要送婚戒才能升到4级，但是没有标识是否送过的字段（只能送过之后Cpbind接口去升级），导致如果婚戒送不成功导致一直是3级无法升级这里其实控制的是当ln_connection_relation表中等级为3时，无法再通过此方法升亲密度，只有把class_name升到4级后才行
                            $classNumber = 3;
                            $gradeNumber = 30;
                            $intimacy = isset($gradeMap[$gradeNumber+1]['exp']) ? abs($gradeMap[$gradeNumber+1]['exp'] - $value['intimacy']) : 0;
                        }
                        break;
                    }
                }
            }
            if ($value['intimacy_last_update_time'] == $date) {
                app('model_connection_relation')
                    ->where('id', $value['id'])
                    ->update([
                        'today_intimacy' => DB::raw('today_intimacy+' . $intimacy),
                        'today_intimacy_free' => DB::raw('today_intimacy_free+' . $intimacy),
                        'intimacy' => DB::raw('intimacy+' . $intimacy),
                        'class_number' => $classNumber,
                        'grade_number' => $gradeNumber,
                    ]);
            } else {
                app('model_connection_relation')
                    ->where('id', $value['id'])
                    ->update([
                        'today_intimacy' => $intimacy,
                        'today_intimacy_free' => $intimacy,
                        'intimacy' => DB::raw('intimacy+' . $intimacy),
                        'class_number' => $classNumber,
                        'grade_number' => $gradeNumber,
                        'intimacy_last_update_time' => $date
                    ]);
            }
            if ($classNumber == 5 && $value['grade_number']<41 && $gradeNumber>=41) {
                $classDetail = $classMap[$value['type']][5];
                $userIds = [$value['user_id'],$value['relation_user_id']];
                $userDataList = app('model_user_data')->whereIn('user_id', $userIds)
                    ->select('user_id','sex')->get()->toArray();
                $userDataMap = array_column($userDataList,null,'user_id');
                $mallConfig = json_decode($classDetail['mall_config'], true);
                if (isset($mallConfig[1])) {
                    if ($value['type'] == 1) {//非CP
                        foreach ($userIds as $uid) {
                            foreach ($mallConfig[1] as $key => $v) {
                                app("repo_mall_products")->give($v['product_id'], $uid, $v['days']??10, true);
                            }
                        }
                    } else {//CP
//                        $productId = 0;
                        foreach ($userIds as $uid) {
//                            if ($productId) {
//                                app("repo_mall_products")->give($productId, $uid, 0, true, true);
//                                continue;
//                            }
                            foreach ($mallConfig[1] as $key => $v) {
//                                if ($userDataMap[$uid]['sex'] == $v['sex']) {
                                app("repo_mall_products")->give($v['product_id'], $uid, 0, true, true);
//                                } else {
//                                    $productId = $v['product_id'];
//                                }
                            }
                        }
                    }
                }
                if (isset($mallConfig[4])) {
                    foreach ($mallConfig[4] as $v) {
                        foreach ($userIds as $uid) {
                            app("repo_mall_products")->give($v['product_id'], $uid, $v['days']??0, true, isset($v['days']) ? false : true);
                        }
                    }
                }
            }
        }
        return ;
    }

    /**
     * 人脉CP绑定申请过期检查 1次/min
     */
    public function cpApplyExpireCheck()
    {
        $list = app('model_connection_cpapply')->where('status', 0)->where('expire_time', '<=', date('Y-m-d H:i:s'))->get()->toArray();
        if (empty($list)) return ;
        $userIds = array_merge(array_column($list,'user_id'), array_column($list,'apply_user_id'));
        $userList = app('model_user')
            ->select('user_id','emchat_username')
            ->whereIn('user_id', $userIds)
            ->get()->toArray();
        $userMap = array_column($userList,null,'user_id');

        $push = new PushService();
        foreach ($list as $value) {
            $pushData = app('model_user')->getPrivateUserInfo($value['apply_user_id']);
            $push->chat->cpApplyExpire($value['user_id'], $pushData, $value['apply_user_id']);

            $pushData = app('model_user')->getPrivateUserInfo($value['user_id']);
            $push->chat->cpApplyExpire($value['apply_user_id'], $pushData, $value['user_id']);
        }
        app('model_connection_cpapply')->whereIn('id', array_column($list,'id'))->update(['status' => 3]);
    }

    //更新首页推荐大神数据和最新大神数据--两分钟一次
    public function cacheRecommendData()
    {
        //更新推荐大神数据
//        $time_end = time();
//        $time_start = $time_end - 86400;
//        //缓存官方推荐数据(待订单更新)
//        $recommend = app('model_lisence_order')->where('status',6)->whereBetween('update_time',[$time_start,$time_end])
//            ->groupBy('ulisence_id')->orderBy(DB::raw('count(*)'),'desc')->pluck('ulisence_id')->toArray();
//
//        if(!empty($recommend))
//        {
//            app('redis')->set('nindex:recommend',json_encode($recommend));
//        } else {
        $recommend = app('model_user_lisence')->where('status', 1);

        if (env('YUTANG_IOS_VERIFY')) {
            $recommend = $recommend->whereHas(
                'lisence',
                function ($query) {
                    $query->where('status', 1);
                }
            );
        }

        $recommend = $recommend->orderBy('total_num', 'desc')->limit(50)->pluck('id')->toArray();

        if (!empty($recommend)) {
            app('redis')->set('nindex:recommend', json_encode($recommend));
        }
//        }

        //更新最新大神数据
        $newlist = app('model_user_lisence')->where('status', 1);

        if (env('YUTANG_IOS_VERIFY')) {
            $newlist = $newlist->whereHas(
                'lisence',
                function ($query) {
                    $query->where('status', 1);
                }
            );
        }

        $newlist = $newlist->orderBy('update_time', 'desc')->limit(50)->pluck('id')->toArray();

        if (!empty($newlist)) {
            app('redis')->set('nindex:newlist', json_encode($newlist));
        }

        return 'ok';
    }


    //定期清除过期的用户key值(一分钟一次)在线的key值
    public function clearExpireOnlineUser()
    {
    }


    //清除过期的接单,账户回款,记录日志(一分钟一次)
    public function clearExpireReceiveOrder()
    {
        $expire_timestamp = time() - Config::get('qipao.const_number.order_expire_time');
        $list = app('model_lisence_order')->where('add_time', '<', $expire_timestamp)->where('status', 1)->get();

        foreach ($list as &$val) {
            //开启事务执行机器取消操作
            $order = app('model_lisence_order')->where('order_id', $val->order_id)->first();

            if ($order->status == 1) {
                //查询用户详情,回钱,记录账户变动日志
                $user = app('repo_order')->getUserDetail($order->user_id);

                $time = time();
                $log_data = [
                    'order_id'  => $order->order_id,
                    'add_time'  => $time,
                    'is_auto'   => 2,
                    'type'      => 2,
                    'memo'      => '接单超时,系统自动取消订单',
                    'memo_type' => 0,
                ];

                //财务变动日志
                $account_data = [
                    'user_id'     => $order->user_id,
                    'user_money'  => $order->price,
                    'change_time' => $time,
                    'change_desc' => '订单超时系统取消订单,用户账户回款',
                    'change_type' => 38,
                    'order_sn'    => $order->order_id,
                ];

                //开启事务去取消订单
                DB::beginTransaction();
                try {
                    //订单状态改变
                    $update_data = [
                        'status'        => 2,
                        'update_time'   => $time,
                        'response_type' => 0,
                        'is_auto'       => 2,
                        'response_memo' => '接单超时,系统自动取消订单',
                    ];
                    $res = app('model_lisence_order')->where('order_id', $val->order_id)->where('status', 1)->update(
                        $update_data
                    );
                    if (!$res) {
                        throw new BasicException(90016);
                    }

                    //回钱
                    $user->money = $user->money + $order->price;
                    $res = $user->save();
                    if (!$res) {
                        throw new BasicException(90016);
                    }

                    //状态改变
//                    $order->status = 2;
//                    $order->update_time = $time;
//                    $order->response_type = 0;
//                    $order->is_auto = 2;
//                    $order->response_memo = '接单超时,系统自动取消订单';
//                    $res = $order->save();
//                    if(!$res) throw new BasicException(90016);
                    //创建财务回款日志
                    app('repo_order')->userAccountAdd($account_data);

                    //创建日志
                    app('repo_order')->orderLogAdd($log_data);

                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack();
                    throw new BasicException(90016);
                }
            }
        }

        return 'ok';
        //function end
    }


    //订单自动退款--一分钟一次
    public function orderAutoRefund()
    {
        $expire_timestamp = time() - Config::get('qipao.const_number.order_refund_time');
        $list = app('model_lisence_order')->where('add_time', '<', $expire_timestamp)->where('status', 8)->get();

        foreach ($list as &$val) {
            //开启事务执行机器取消操作
            $order = app('model_lisence_order')->where('order_id', $val->order_id)->first();

            if ($order->status == 8) {
                //查询用户详情,回钱,记录账户变动日志
                $user = app('repo_order')->getUserDetail($order->user_id);

                $time = time();
                $log_data = [
                    'order_id'  => $order->order_id,
                    'add_time'  => $time,
                    'is_auto'   => 2,
                    'type'      => 9,
                    'memo'      => '退款处理超时,系统自动退款',
                    'memo_type' => 0,
                ];

                //财务变动日志
                $account_data = [
                    'user_id'     => $order->user_id,
                    'user_money'  => $order->price,
                    'change_time' => $time,
                    'change_desc' => '退款处理超时系统自动退款,用户账户回款',
                    'change_type' => 39,
                    'order_sn'    => $order->order_id,
                ];

                //开启事务去取消订单
                DB::beginTransaction();
                try {
                    //订单状态改变
                    $update_data = [
                        'status'        => 9,
                        'update_time'   => $time,
                        'response_type' => 0,
                        'is_auto'       => 2,
                        'response_memo' => '退款处理超时,系统自动退款',
                    ];
                    $res = app('model_lisence_order')->where('order_id', $val->order_id)->where('status', 8)->update(
                        $update_data
                    );
                    if (!$res) {
                        throw new BasicException(90019);
                    }


                    //回钱
                    $user->money = $user->money + $order->price;
                    $res = $user->save();
                    if (!$res) {
                        throw new BasicException(90019);
                    }

                    //状态改变
//                    $order->status = 9;
//                    $order->update_time = $time;
//                    $order->response_type = 0;
//                    $order->response_memo = '退款处理超时,系统自动退款';
//                    $order->is_auto = 2;
//                    $res = $order->save();
//                    if(!$res) throw new BasicException(90019);
                    //创建财务回款日志
                    app('repo_order')->userAccountAdd($account_data);

                    //创建日志
                    app('repo_order')->orderLogAdd($log_data);

                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack();
                    throw new BasicException(90019);
                }
            }
        }

        return 'ok';
        //method end
    }


    //退款拒绝未确认自动完结订单
    public function completeRefundOrder()
    {
        $expire_timestamp = time() - Config::get('qipao.const_number.order_refuse_time');
        $list = app('model_lisence_order')->where('add_time', '<', $expire_timestamp)->where('status', 10)->where(
            'is_settlement',
            1
        )->get();

        foreach ($list as &$val) {
            //开启事务执行机器取消操作
            $order = app('model_lisence_order')->where('order_id', $val->order_id)->first();

            if ($order->status == 10) {
                //查询用户详情,回钱,记录账户变动日志
                $user = app('repo_order')->getUserDetail($order->uid);

                $price = floor($order->price * (100 - $order->rate_platform) / 100);

                $time = time();
                $log_data = [
                    'order_id'  => $order->order_id,
                    'add_time'  => $time,
                    'is_auto'   => 2,
                    'type'      => 22,
                    'memo'      => '用户确认拒绝退款超时,系统结算订单',
                    'memo_type' => 0,
                ];

                //财务变动日志
                $account_data = [
                    'user_id'     => $order->uid,
                    'user_money'  => $price,
                    'change_time' => $time,
                    'change_desc' => '系统结算订单,大神账户入账',
                    'change_type' => 40,
                    'order_sn'    => $order->order_id,
                ];

                //查询公会信息
                $sociaty_id = app('repo_order')->getUserSociatyId($order->uid);

                //开启事务去取消订单
                DB::beginTransaction();
                try {
                    //订单状态改变
                    $update_data = [
                        'sociaty_id'    => $sociaty_id['sociaty_id'],
                        'hall_id'       => $sociaty_id['hall_id'],
                        'is_settlement' => 2,
                        'rate_sociaty'  => Config::get('qipao.order_rate.sociaty'),
                        'status'        => 6,
                        'update_time'   => $time,
                        'response_type' => 0,
                        'is_auto'       => 2,
                        'response_memo' => '用户确认拒绝退款超时,系统结算订单',
                    ];
                    $res = app('model_lisence_order')->where('order_id', $val->order_id)->where('status', 10)->update(
                        $update_data
                    );
                    if (!$res) {
                        throw new BasicException(90023);
                    }


                    //回钱
                    $user->earnings = $user->earnings + $price;
                    $res = $user->save();
                    if (!$res) {
                        throw new BasicException(90023);
                    }

                    //状态改变
//                    $order->sociaty_id = $sociaty_id['sociaty_id'];
//                    $order->hall_id = $sociaty_id['hall_id'];
//                    $order->is_settlement = 2;
//                    $order->rate_sociaty = Config::get('qipao.order_rate.sociaty');
//                    $order->status = 6;
//                    $order->update_time = $time;
//                    $order->response_type = 0;
//                    $order->response_memo = '用户确认拒绝退款超时,系统结算订单';
//                    $order->is_auto = 2;
//                    $res = $order->save();
//                    if(!$res) throw new BasicException(90023);
                    //创建财务回款日志
                    app('repo_order')->userAccountAdd($account_data);

                    //创建日志
                    app('repo_order')->orderLogAdd($log_data);

                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack();
                    throw new BasicException(90023);
                }
            }
        }

        return 'ok';
        //method end
    }


    //结算订单--一分钟一次
    public function completeOrder()
    {
        $expire_timestamp = time() - Config::get('qipao.const_number.order_complete_time');
        $list = app('model_lisence_order')->where('add_time', '<', $expire_timestamp)->whereIn('status', [4, 5])->where(
            'is_settlement',
            1
        )->get();

        foreach ($list as &$val) {
            //开启事务执行机器取消操作
            $order = app('model_lisence_order')->where('order_id', $val->order_id)->first();

            if (($order->status == 4) || ($order->status == 5)) {
                //查询用户详情,回钱,记录账户变动日志
                $user = app('repo_order')->getUserDetail($order->uid);

                $price = floor($order->price * (100 - $order->rate_platform) / 100);

                $time = time();
                $log_data = [
                    'order_id'  => $order->order_id,
                    'add_time'  => $time,
                    'is_auto'   => 2,
                    'type'      => 21,
                    'memo'      => '系统结算订单',
                    'memo_type' => 0,
                ];

                //财务变动日志
                $account_data = [
                    'user_id'     => $order->uid,
                    'user_money'  => $price,
                    'change_time' => $time,
                    'change_desc' => '系统结算订单,大神账户入账',
                    'change_type' => 40,
                    'order_sn'    => $order->order_id,
                ];


                //查询公会信息
                $sociaty_id = app('repo_order')->getUserSociatyId($order->uid);

                //开启事务去取消订单
                DB::beginTransaction();
                try {
                    //订单状态改变
                    $update_data = [
                        'sociaty_id'    => $sociaty_id['sociaty_id'],
                        'hall_id'       => $sociaty_id['hall_id'],
                        'is_settlement' => 2,
                        'rate_sociaty'  => Config::get('qipao.order_rate.sociaty'),
                        'status'        => 6,
                        'update_time'   => $time,
                        'response_type' => 0,
                        'is_auto'       => 2,
                        'response_memo' => '系统结算订单',
                    ];
                    $res = app('model_lisence_order')->where('order_id', $val->order_id)->whereIn(
                        'status',
                        [4, 5]
                    )->update($update_data);
                    if (!$res) {
                        throw new BasicException(90023);
                    }


                    //回钱
                    $user->earnings = $user->earnings + $price;
                    $res = $user->save();
                    if (!$res) {
                        throw new BasicException(90023);
                    }

                    //状态改变
//                    $order->sociaty_id = $sociaty_id['sociaty_id'];
//                    $order->hall_id = $sociaty_id['hall_id'];
//                    $order->is_settlement = 2;
//                    $order->rate_sociaty = Config::get('qipao.order_rate.sociaty');
//                    $order->status = 6;
//                    $order->update_time = $time;
//                    $order->response_type = 0;
//                    $order->response_memo = '系统结算订单';
//                    $order->is_auto = 2;
//                    $res = $order->save();
//                    if(!$res) throw new BasicException(90023);

                    //更新user_lisence的信息(单量和好评)
                    app('repo_order')->updateUserLisence($order->ulisence_id, $order->order_num);

                    //创建财务回款日志
                    app('repo_order')->userAccountAdd($account_data);

                    //创建日志
                    app('repo_order')->orderLogAdd($log_data);

                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack();
                    throw new BasicException(90023);
                }
            }
        }

        return 'ok';
        //method end
    }


    //自动审核的脚本(一分钟一次)
    public function autoVerifyUserLisence()
    {
        //只审核符合条件的,并且通过提交审核
        $list = app('model_lisence_apply')->where('is_show', 1)->get();

//        $str = "[9, 10, 11]";
//        dd(json_decode($str));
        //拿到所有的tag_ids

        foreach ($list as &$nal) {
            //审核tag_images
            $images = json_decode($nal->tag_image, true);
//            dd($images);
            if (is_array($images) && !empty($images)) {
                $tag_ids = [];
                //拿到所有tag_ids
                foreach ($images as $key => $val) {
                    if (is_numeric($key)) {
                        $tag_ids[] = $key;
                    }
                    if (is_numeric($val)) {
                        $tag_ids[] = intval($val);
                    }

                    if (is_array($val)) {
                        foreach ($val as $kal) {
                            if (is_numeric($kal)) {
                                $tag_ids[] = $kal;
                            }
                        }
                    }
                }

                //查询所有tag_id的信息
                $tags = app('model_lisence_tag')->whereIn('tag_id', $tag_ids)
//                    ->where('lisence_id',$nal->lisence_id)
                    ->select(
                        'tag_id',
                        'lisence_id',
                        'pid',
                        'level',
                        'status',
                        'option',
                        'is_select',
                        'requirement'
                    )->get()->toArray();

                $tagArr = [];
                foreach ($tags as $cal) {
                    $tagArr[$cal['tag_id']] = $cal;
                }

//                dd($tagArr);

                //最后一遍循环来校验id是否合法
                $final_tag_ids = [];
                $is_pass = false;       //最终是否通过的标签
                $verify_memo = '';      //理由
                foreach ($images as $key => $val) {
//                    if(is_numeric($key) && isset($tagArr[$key]) && ($tagArr[$key]['pid'] == 0)) {
                    if (is_numeric($key) && isset($tagArr[$key]) && ($tagArr[$key]['pid'] == 0)) {
                        $final_tag_ids[] = $key;
                    }
                    if (is_numeric($val) && isset($tagArr[$val]) && ($tagArr[$val]['pid'] != 0)) {
                        $final_tag_ids[] = intval($val);
                    }


                    if (is_array($val)) {
                        foreach ($val as $kal) {
                            if (is_numeric($kal) && isset($tagArr[$kal]) && ($tagArr[$kal]['pid'] != 0)) {
                                $final_tag_ids[] = intval($kal);
                            }
                        }
                    }
                    //一级是数值,存在标签,且是一级就通过

                    //半人工

//                        if($tagArr[$key]['pid']['requirement'] == 1)
//                        {
//                            if(!empty($val)) {
//                                if($tagArr[$key]['pid']['option'] == 1)
//                                {
//
//                                }
//
//                            } else {
//                                break 2;
//                            }
//                        }

//                    } else {
//                        break 2;
//                    }
                }

                $apply = app('model_lisence_apply')->where('id', $nal->id)->first();
                $apply->tag_ids = implode(',', $final_tag_ids);
                $apply->save();
                //one images end
            } else {
                $apply = app('model_lisence_apply')->where('id', $nal->id)->first();
                $apply->is_show = 2;
                $apply->save();
            }
            //loop end
        }

        return 'ok';
        //method end
    }


    public function verifyFailed()
    {
    }

    //发放周星奖励
    private function grantWeekStarReward($rank_list, $reward_info, $gift_info)
    {
        if (empty($reward_info)) {
            return;
        }
        $send_type = $gift_info['send_type'];
        $model_gift_backpack = app('model_gift_backpack');
        $model_mall_orders = app('model_mall_orders');
        $model_room_background_buy_log = app("model_room_background_buy_log");
        //奖励规则化处理
        $end_info = $reward_info->last();
        $end_ranking = explode('-', $end_info->ranking);
        if (empty($end_ranking)) {
            return;
        }
        $end = end($end_ranking);
        $rank_list = array_column(array_slice($rank_list, 0, $end), NULL, 'rank');

        $time = time();
        foreach ($reward_info as $info) {
            $rank_ary = explode('-', $info->ranking);
            $start_i = reset($rank_ary);
            $end_i = end($rank_ary);
            for ($i = $start_i; $i<= $end_i; $i++) {
                $user_rank = $rank_list[$i] ?? [];
                if (empty($user_rank)) {
                    continue;
                }
                if ($info->relation_type == 'App\Models\MainDB\MallProducts') {
                    $model_mall_orders->addProduct((int)$user_rank['user_id'], (int)$info->relation_id, (int)$info->count, (int)$info->relation->category_id);
                } else if ($info->relation_type == 'App\Models\MainDB\Gift') {
                    $model_gift_backpack->addGift((int)$user_rank['user_id'], (int)$info->relation_id, (int)$info->count);
                } else if ($info->relation_type == 'App\Models\MainDB\RoomBackground') {
                    $expire_time = $info->count * 86400;
                    $buy_log_info = app("model_room_background_buy_log")
                        ->where(['use_user_id' => $user_rank['user_id'], 'room_background_id' => $info->relation->id])
                        ->first();
                    if (empty($buy_log_info)) {
                        $model_room_background_buy_log->create([
                            'buy_user_id'          => $user_rank['user_id'],
                            'buy_user_name'        => '',
                            'use_user_id'          => $user_rank['user_id'],
                            'use_user_name'        => '',
                            'room_background_id'   => $info->relation->id,
                            'room_background_name' => $info->relation->name,
                            'add_time'             => $time,
                            'price'                => floatval($price ?? 0),
                            'day'                  => $info->count,
                            'picture'              => $info->relation->picture,
                            'effect_picture'       => $info->relation->effect_picture,
                            'overdue_time'         => $time + $expire_time,
                            'renew_number'         => 0
                        ]);
                    } else {
                        $model_room_background_buy_log->where('id', $buy_log_info['id'])
                            ->update([
                                'overdue_time' => ($buy_log_info['overdue_time'] > $time ? $buy_log_info['overdue_time'] : $time) + $expire_time,
                                'day'          => $buy_log_info['day'] + $info->count,
                                'state'        => 1,
                            ]);
                    }
                    app('repo_room_background')->setRoomBackground($info->relation, $user_rank['user_id'], $user_rank['room_id'], $expire_time);
                } else {
                    continue;
                }
            }
        }

        //type 1贡献榜 2魅力榜 3房间榜
        foreach ($rank_list as $k => $user_rank)
        {
            $news_info = '恭喜您！在上周周星争夺战中，';
            if ($send_type == 1) {
                $news_info .= "通过赠送「{$gift_info['name']}」礼物获得第{$k}名，奖励已发放至您的背包，请注意查收。";
            } else if ($send_type == 2) {
                $news_info .= "通过收到「{$gift_info['name']}」礼物获得第{$k}名，奖励已发放至您的背包，请注意查收。";
            } else {
                $news_info .= "您的房间获得第{$k}名，奖励已发放。";
            }
            //系统消息
            app('model_user_news')->sendUserNews($user_rank['user_id'], '周星奖励', $news_info);
        }
    }

    //周星榜数据入库 上周
    public function saveWeekStar()
    {
        if (!app('redis')->set('weekstar:lock_key', 'lock', 'ex', 60, 'nx')) {
            echo '60s缓存';
            return;
        }
        $weeks = date('oW', strtotime('-1 week'));

        $week_star_info = app('model_week_star')->where(['weeks' => $weeks, 'deleted' => 0, 'is_status' => 0])->first();

        if (!$week_star_info) {
            return;
        }

        $gift_ids = explode(',', $week_star_info->gift_ids);
        $gift_list = app('model_gift')->whereIn('id', $gift_ids)->selectRaw('id,name')->get()->toArray();
        $gift_list = array_column($gift_list, NULL, 'id');
        $reward_rich = app('model_week_star_reward')->with('relation')
            ->where([/*'week_star_id' => $week_star_info->id,*/ 'type' => 1])
            ->orderBy('ranking', 'asc')->get();
        $reward_charm = app('model_week_star_reward')->with('relation')
            ->where([/*'week_star_id' => $week_star_info->id,*/ 'type' => 2])
            ->orderBy('ranking', 'asc')->get();

        $insert = [];
        foreach ($gift_ids as $gift_id) {
            $key_rich  = 'weekstar:rich:'. $weeks. ':'.$gift_id;
            $key_charm = 'weekstar:charm:'.$weeks. ':'.$gift_id;
            $list_rich = app('redis')->zrevrange($key_rich, 0, -1, "WITHSCORES");
            $list_charm = app('redis')->zrevrange($key_charm, 0, -1, "WITHSCORES");

            $rank_charm = $rank_rich = [];

            $rank = 1;
            foreach ($list_rich as $user_id => $total) {
                $total = getValueByScore($total);
                $rank_rich[] = $insert[] = [
                    'week_star_id' => $week_star_info->id,
                    'user_id'      => $user_id,
                    'room_id'      => 0,
                    'type'         => 1,
                    'rank'         => $rank,
                    'total'        => $total,
                    'gift_id'      => $gift_id,
                ];
                $rank++;
            }
            if (!empty($rank_rich)) {
                $this->grantWeekStarReward($rank_rich, $reward_rich, array_merge($gift_list[$gift_id], ['send_type' => 1]));
            }

            $rank = 1;
            foreach ($list_charm as $user_id => $total) {
                $total = getValueByScore($total);
                $rank_charm[] = $insert[] = [
                    'week_star_id' => $week_star_info->id,
                    'user_id'      => $user_id,
                    'room_id'      => 0,
                    'type'         => 2,
                    'rank'         => $rank,
                    'total'        => $total,
                    'gift_id'      => $gift_id,
                ];
                $rank++;
            }
            if (!empty($rank_charm)) {
                $this->grantWeekStarReward($rank_charm, $reward_charm, array_merge($gift_list[$gift_id], ['send_type' => 2]));
            }
//            app('redis')->del([$key_charm, $key_rich]);
        }

        $key_room = 'weekstar:room:'.$weeks;
        $list_room = app('redis')->zrevrange($key_room, 0, -1, "WITHSCORES");


        $reward_room = app('model_week_star_reward')->with('relation')
            ->where([/*'week_star_id' => $week_star_info->id,*/ 'type' => 3])
            ->orderBy('ranking', 'asc')->get();
        $rank = 1;
        $rank_room = [];
        $room_list = app('model_user_room')->selectRaw('id,user_id')->whereIn('id', array_keys($list_room))->get()->toArray();
        $room_list = array_column($room_list, NULL, 'id');

        foreach ($list_room as $room_id => $total) {
            $total = getValueByScore($total);
            $rank_room[] = $insert[] = [
                'week_star_id' => $week_star_info->id,
                'user_id'      => $room_list[$room_id]['user_id'] ?? 0,
                'room_id'      => $room_id,
                'type'         => 3,
                'rank'         => $rank,
                'total'        => $total,
                'gift_id'      => 0,
            ];
            $rank++;
        }
        if (!empty($rank_room)) {
            $this->grantWeekStarReward($rank_room, $reward_room, ['send_type' => 3]);
        }
        app('model_week_star_history')->insert($insert);
//        app('redis')->del($key_room);
        //更改结算状态
        $week_star_info->is_status = 1;
        $week_star_info->save();
    }

    // 前一日在线用户数计算
    public function onlineUserCompute($command) {
        $obj = Carbon::create();
        $time = $obj->copy()->subDay()->startOfDay()->timestamp;

        $number = UserCacheService::getOnlineUserCount($time);

        $date = $obj->copy()->subDay()->format("Y-m-d");

        $nowTime = time();

        app("model_data_user_online_daily")->create([
            "date" => $date,
            "number" => $number,
            "create_time" => $nowTime,
            "update_time" => $nowTime
        ]);

    }

    public function queryAliAuth()
    {
        $already_auth_users = app('repo_user_auth')->getAuthUsers();
        $timestamp_before = Carbon::now()->addMinutes(-3)->timestamp;
        $list = app('model_alipay_auth')->where('status', 0)->where('add_time', '<=', $timestamp_before)->orderBy('id', 'desc')->limit(100)->get();
        $now_time = Carbon::now()->timestamp;
        foreach ($list as $key => $data) {
            if (isset($already_auth_users[$data->user_id])) {
                app('model_alipay_auth')->where('status', 0)->where('id', $data->id)->update(
                    ['status' => 1, 'update_time' => $now_time]
                );
            } else {
                $status = AliyunService::queryAuthResult($data->certify_id);
                app('model_alipay_auth')->where('status', 0)->where('id', $data->id)->update(
                    ['status' => $status, 'update_time' => $now_time]
                );

                if ($status == 1) {
                    app('model_user_auth')->create(
                        [
                            'user_id'      => $data->user_id,
                            'full_name'    => $data->cert_name,
                            'id_number'    => $data->cert_no,
                            'app_status'   => $status,
                            'created_time' => Carbon::now(),
                            'update_time'  => Carbon::now(),
                            'type'         => 2,
                        ]
                    );
                }
            }
        }
    }


    // 向客户端推送当前参与话题的人数
    public function pushThemeJoinUserNumber($command) {
        $curTheme = app("repo_theme")->getCurTheme();
        $themeId = $curTheme['id'];
        $joinUserNumber = app("repo_theme")->getThemeJoinUserCount($themeId);

        // 发送mqtt
        (new PushService())->themeJoinUserNumber([
            "join_user_count" => $joinUserNumber,
            "theme_id" => $themeId
        ]);

    }

    // 刷新房间热度
    public function refreshRoomPopularity($targetMin, $command) {
        $command->info("刷新" . $targetMin . "的房间热度数据！");

        app("repo_room")->updateRoomPopularity($targetMin, $command);
    }

    // 刷新热门推荐列表
    public function refreshHotList($targetMin, $command) {
        $command->info("刷新" . $targetMin . "的热门列表数据！");

        $repo = app("repo_recommend");
        $enableRoom = $repo->getEnableRoom();
        $enableAnchor = $repo->getEnableAnchor();
        app("repo_recommend")->refreshHotList($targetMin, $command, $enableRoom, $enableAnchor);
    }


    //充值异常监控报警
    public function user_recharge_sentry()
    {
        //查询一分钟之内的充值笔数
        $end_at = time();

        $start_at = $end_at - 60;

        $data = app('model_user_recharge')->whereBetween('add_time',[$start_at,$end_at])->where('status',1)->whereIn('type',[4,5])
            ->select('user_id',DB::raw('count(*) as count'))->withOnly('user_data',['user_id','user_code'])->groupBy('user_id')->get()->toArray();

        foreach($data as $val)
        {
            if($val['count'] >= 3) {

                $code = isset($val['user_data']['user_code']) ? $val['user_data']['user_code'] : $val['user_id'];

                \App\Services\Tools\SmsService::sentryToAdmin($code);
            }
        }


        $data = app('model_user_recharge')->whereBetween('add_time',[$start_at,$end_at])->whereIn('type',[4,5])
            ->select('user_id',DB::raw('count(*) as count'))->withOnly('user_data',['user_id','user_code'])->groupBy('user_id')->get()->toArray();

        foreach($data as $val)
        {
            if($val['count'] >= 5) {

                $code = isset($val['user_data']['user_code']) ? $val['user_data']['user_code'] : $val['user_id'];

                \App\Services\Tools\SmsService::sentryToAdmin($code);
            }
        }


    }

    //账户异常报警
    public function account_sentry()
    {

        //查询一分钟之内的账户变动日志
        $end_at = time();

        $start_at = $end_at - 60;

        $data = app('model_account_log')->whereBetween('change_time',[$start_at,$end_at])->whereNotIn('change_type',[1,6])->select('user_id')
            ->withOnly('user_data',['user_id','user_code'])
            ->withCount('user_recharges')
            ->groupBy('user_id')->get()->toArray();

        //查看所有公会uid
        $sociaty_user = app('model_sc_sociaty_user')->pluck('user_id')->toArray();

        foreach($data as $val)
        {

            if(!in_array($val['user_id'],$sociaty_user)) {

                //非公会成员报警
                if($val['user_recharges_count'] <= 0) {
                    //没有充值记录就报警,并且封禁账号

                    $code = isset($val['user_data']['user_code']) ? $val['user_data']['user_code'] : $val['user_id'];

                    \App\Services\Tools\SmsService::sentryToAdminByAccount($code);

                    //todo:暂时不封禁用户,先跑一段时间
                }

            }

        }

    }

    //缓存首页广告数据
    public function updateIndexAdvertisement()
    {
        $time = time();
        $list = app('model_index_adv')->where('status',1)
            ->where('start_at','<',$time)->where('end_at','>',$time)
            ->select('id','url','link_url','format','sec','room_id','type','format')
            ->get()->toArray();

        foreach($list as $key=>$val)
        {
            $list[$key]['content'] = ($val['type'] == 1) ? $val['link_url'] : $val['room_id'];
            unset($list[$key]['link_url']);
            unset($list[$key]['room_id']);
        }

        $json_str = json_encode($list);

        app('redis')->set('nindex:advertisement',$json_str);
    }

    //个性商城过期物品 、 过期爵位 、 过期房间背景
    public function dress()
    {
        $list = app('model_mall_orders')
            ->where('state', '!=', 2)
            ->where('expired_time', '>', 0)
            ->where('expired_time', '<', time())
            ->get();
        if (!$list->isEmpty()) {
            $list = $list->toArray();
            $ids = [];
            $userCodeIds = [];
            foreach ($list as $val) {
                $ids[] = $val['id'];
                $redis_key = '';
                if ($val['category_id'] == MallEnum::JOIN_CATEGORY_ID) {
                    $redis_key = RedisKeyEnum::USER_JOIN_SPECIAL.$val['user_id_owner'];
                } elseif ($val['category_id'] == MallEnum::RIDE_CATEGORY_ID) {
                    $redis_key = RedisKeyEnum::USER_RIDE.$val['user_id_owner'];
                } elseif ($val['category_id'] == MallEnum::AVATAR_CATEGORY_ID) {
                    $redis_key = RedisKeyEnum::USER_HP.$val['user_id_owner'];
                } elseif ($val['category_id'] == MallEnum::CATEGORY_ID_CHAT_BUBBLE) {
                    $redis_key = RedisKeyEnum::USER_CHAT_BUBBLE.$val['user_id_owner'];
                } elseif ($val['category_id'] == MallEnum::CATEGORY_ID_ROOM_CHAT_BUBBLE) {
                    $redis_key = RedisKeyEnum::USER_ROOM_CHAT_BUBBLE.$val['user_id_owner'];
                } elseif ($val['category_id'] == MallEnum::CATEGORY_ID_GLOBAL_BROADCAST) {
                    $redis_key = RedisKeyEnum::USER_GLOBAL_BROADCAST.$val['user_id_owner'];
                } elseif ($val['category_id'] == MallEnum::CATEGORY_ID_SOUND_WAVE) {
                    $redis_key = RedisKeyEnum::USER_SOUND_WAVE.$val['user_id_owner'];
                } elseif ($val['category_id'] == MallEnum::CATEGORY_ID_NICKNAME_SPECIAL) {
                    $redis_key = RedisKeyEnum::USER_NICKNAME_SPECIAL.$val['user_id_owner'];
                } elseif ($val['category_id'] == MallEnum::NICKNAME_CATEGORY_ID) {
                    $redis_key = RedisKeyEnum::USER_NICKNAME.$val['user_id_owner'];
                } elseif ($val['category_id'] == MallEnum::CATEGORY_ID_CARD_FRAME) {
                    $redis_key = RedisKeyEnum::USER_CARD_FRAME.$val['user_id_owner'];
                } else {
                    $product = app("model_mall_products")->where('id', $val['product_id'])->first();
                    $product_category = $product->category ?? null;
                    if ($product_category) {
                        $rootCategory = $product_category->getRootCategory();
                        if ($rootCategory && $rootCategory->id === MallEnum::CODE_ROOT_CATEGORY_ID) {
                            $userCodeIds[] = array_pop($ids);
                        }
                    }
                }
                RedisService::clearUserInfo($val['user_id_owner']);
                if ($redis_key && $val['state'] == 1) {
                    app('redis')->del($redis_key);
                }
            }
            if ($ids) {
                app('model_mall_orders')->whereIn('id', $ids)->update(['state' => 2]);
            }
            if ($userCodeIds) {
                $this->userCodeExpired($userCodeIds);
            }
        }

        /*$list1 = app('model_user_nobility')
            ->where('state', '!=', 2)
            ->where('expired_time', '<', time())
            ->get();
        if (!$list1->isEmpty()) {
            $user_ids = $ids = [];
            foreach ($list1 as $val) {
                $user_ids[] = $val['user_id'];
                $ids[] = $val['id'];
                RedisService::clearUserInfo($val['user_id']);
                RedisService::delUserNobility($val['user_id']);
            }
            app('model_user_nobility')->whereIn('id', $ids)->update(['state' => 2]);
            //app('model_user_nobility')->close_privilege($user_ids);
            app('model_user')->whereIn('user_id', $user_ids)->update(['nobility' => 0]);
        }*/
        $this->expireNobility();
        $this->expireRoomBackground();
    }

    public function expireNobility()
    {
        $model_user_nobility = app('model_user_nobility');
        $model_nobility = app('model_nobility');
        $time = time();
        $model_user = app('model_user');
        $model_user_config = app('model_user_config');
        $nobility_save = $user_config_save = [];
        #获得过期的用户爵位
        $list = $model_user_nobility->from($model_user_nobility->getTable(). ' as t1')
            ->selectRaw('t1.*, t2.grade, t2.privilege')
            ->join($model_nobility->getTable() . " as t2", "t1.nobility_id", "=", "t2.id")
            ->where('state', 1)
            ->where('expired_time', '<=', $time)
            ->orderBy('t2.grade', 'asc')->get();
        if ($list->isEmpty()) {
            return;
        }
        $ids = array_column($list->toArray(), 'id');
        $group_user_ids = $list->groupBy('user_id')->keys()->toArray();
        //获得未过期的用户爵位
        $group_list_last = $model_user_nobility->from($model_user_nobility->getTable(). ' as t1')
            ->selectRaw('t1.*, t2.grade, t2.privilege')
            ->join($model_nobility->getTable() . " as t2", "t1.nobility_id", "=", "t2.id")
            ->where('state', 1)
            ->whereIn('user_id', $group_user_ids)
            ->where('expired_time', '>', $time)
            ->orderBy('t2.grade', 'desc')->get()->groupBy('user_id')->toArray();
        #隐私设置的key-ID
        $invisibleKey = app('model_nobility_privilege')->getInvisibleKey();
        foreach ($group_user_ids as $val) {
            RedisService::clearUserInfo($val);
            RedisService::delUserNobility($val);
            //获得最高爵位
            $one = ['nobility_id' => 0, 'grade' => 0];
            if (isset($group_list_last[$val])) {
                $one = reset($group_list_last[$val]);
            }
            $nobility_save[$one['nobility_id']][] = $val;
            $l_nobility = $nobility_list[$one['grade']] ?? [];
            if (empty($l_nobility)) {
                $user_config_save[$val] = ['is_invisible' => 0, 'rank_invisible' => 0];
            } else {
                $privilege = explode(',', $l_nobility['privilege']);
                if (!in_array($invisibleKey, $privilege)) {
                    $user_config_save[$val] = ['is_invisible' => 0, 'rank_invisible' => 0];
                }
            }
        }
        app('model_user_nobility')->whereIn('id', $ids)->update(['state' => 2]);
        foreach ($nobility_save as $key => $user_ids) {
            $model_user->whereIn('user_id', $user_ids)->update(['nobility' => $key]);
        }
        //清除爵位的隐私设置
        foreach ($user_config_save as $user_id => $save_config) {
            $model_user_config->where('user_id', $user_id)->update($save_config);
        }

    }

    public function expireRoomBackground()
    {
        $model = app('model_room_background_buy_log');
        $list = $model->where([
            'state' => 1,
            ['overdue_time', '<', time()],
        ])->get()->toArray();
        if (empty($list)) {
            return true;
        }
        $user_ids = array_column($list, 'use_user_id');
        $room_list = app('model_user_room')->selectRaw('id,user_id')->whereIn('user_id', $user_ids)->get()->toArray();
        $room_list = array_column($room_list, NULL, 'user_id');
        $backgroundInfo = app('model_room_background')->where('is_default', 1)->first();
        foreach ($list as $ary) {
            $user_id = $ary['use_user_id'];
            $roomId = $room_list[$user_id]['id'];
            app('repo_room_background')->setRoomBackground($backgroundInfo, $user_id, $roomId);
            $model->where('id', $ary['id'])->update(['state' => 2]);
        }
    }

    protected function userCodeExpired(array $ids)
    {
        $models = app('model_mall_orders')->whereIn('id', $ids)->get();

        foreach ($models as $model) {
            $user = app('model_user_data')->where('user_id', $model->user_id_owner)->first();
            if (isset($user->is_use_code)) {
                $lastUserCode = $user->user_code;
                $user->user_code = $user->last_user_code;
                $user->last_user_code = $lastUserCode;
                $user->is_use_code = 0;
                $user->save();
                $product = app("model_mall_products")->where('id', $model->product_id)->first();
                $product->on_sale = 1;
                $product->save();

                app('redis')->hdel('goodNumber', $user->user_code);
            }
        }
        app('model_mall_orders')->whereIn('id', $ids)->update(['state' => 2]);
    }

    //电台 守护 到期更新状态
    public function protect()
    {
        app('model_fm_protect_list')->whereRaw('expired_time <= '.time())->update(['state' => 2]);
        $list = app('model_fm_protect')->whereRaw('expired_time <= ' . time() . ' and state = 1')->get()->toArray();
        foreach ($list as $val) {
            $protect_list = app('model_fm_protect_list')->where([
                'user_id'         => $val['user_id'],
                'user_id_protect' => $val['user_id_protect'],
                'room_id'         => $val['room_id'],
                'state'           => 1,
            ])->orderByRaw('type asc, expired_time desc')->get()->toArray();
            if (!empty($protect_list)) {
                $i = 1;
                $json_type = [];
                $update_data = [];
                foreach ($protect_list as $k => $detail) {
                    if ($i == 1) {
                        $update_data = [
                            'type'         => $detail['type'],
                            'expired_time' => $detail['expired_time'],
                            'update_time'  => time(),
                        ];
                    }
                    $json_type [] = ['type' => $detail['type']];
                    $i++;
                }
                if ($json_type) {
                    $update_data['protect_info'] = json_encode($json_type);
                }
                if ($update_data) {
                    app('model_fm_protect')->where('id', $val['id'])->update($update_data);
                }
            } else {
                app('model_fm_protect')->where('id', $val['id'])->update([
                    'update_time' => time(),
                    'state'       => 2,
                ]);
            }
        }
    }

    public function updatePopularity() {
        $list= app('model_room_online_user')->groupBy('room_id')->selectRaw('sum(popularity) total, room_id')->get()->toArray();
        $room_id_array = array_column($list, 'room_id');
        $timestamp = Carbon::now()->addMinutes('-10')->timestamp;
        if (!$room_id_array) {
            echo '无数据';
        }
        $give_gift_list = app('model_give_gift')->whereIn('room_id', $room_id_array)->where('add_time', '>=', $timestamp)->groupBy('room_id')->selectRaw('sum(total_price) total, room_id')->get()->keyBy('room_id')->toArray();

        foreach ($list as $value) {
            $room_id = $value['room_id'];
            $popularity = $value['total'];

            $gold =$give_gift_list[$room_id]['total'] ?? 0;
            $popu_gift = round($gold / 20);

            $correct_popu = $popularity + $popu_gift;

            $current_popularity = app('redis')->get('room:popularity:'.$room_id);

            if ($correct_popu <> $current_popularity) {
                app('redis')->set('room:popularity:'.$room_id, $correct_popu);
                echo $room_id,':', $correct_popu, '|', $current_popularity . "<br>";
            }
        }
    }
}
